package com.example.helper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.utils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.Map;
import java.util.Optional;

/**
 * @author twy12138
 * @description: 分页查询抽象接口实现
 */
@Service
public abstract class AbstractPageServiceImpl<T> implements PageService<T> {

    private final String PAGE_SIZE = "pageSize";

    private final String CURRENT_PAGE = "currentPage";

    @Autowired
    private BaseMapper<T> mapper;

    public void beforePageQuery(Object param) {
    }

    public IPage<T> afterPageQuery(IPage<T> iPage) {
        return iPage;
    }

    public IPage<T> pageQuery(Object param) {
        try {
            beforePageQuery(param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        IPage<T> iPage;
        Map<String, Object> convertParam = BeanUtils.bean2Map(param);
        if (CollectionUtils.isEmpty(convertParam)) {
            return new Page<>();
        }
        int pageSize = Optional.ofNullable(convertParam.get(PAGE_SIZE)).map(Object::toString).map(Integer::parseInt).orElse(0);
        int pageNum = Optional.ofNullable(convertParam.get(CURRENT_PAGE)).map(Object::toString).map(Integer::parseInt).orElse(0);
        if (pageNum == 0 || pageSize == 0) {
            return new Page<>();
        }
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        Page<T> page = new Page<>(pageNum, pageSize);
        iPage = mapper.selectPage(page, wrapper);
        try {
            iPage = afterPageQuery(iPage);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return iPage;
    }

}
